import React from 'react';
import { Editor } from 'react-draft-wysiwyg';
import { convertToRaw, ContentState, EditorState } from 'draft-js';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import request from '@/http';
import CONSTANT from '@/constant';

interface RichTextProps {
  value?: string;
  onChange?: (value: string) => void;
}

export default class RichText extends React.Component<
  RichTextProps,
  { editorState: any }
> {
  constructor(props: RichTextProps) {
    super(props);
    this.onEditorStateChange = this.onEditorStateChange.bind(this);
    let editorState;
    if (props.value) {
      const contentBlock = htmlToDraft(props.value);
      const contentState = ContentState.createFromBlockArray(
        contentBlock.contentBlocks,
      );
      editorState = EditorState.createWithContent(contentState);
    } else {
      editorState = EditorState.createEmpty();
    }
    this.state = {
      editorState,
    };
  }

  onEditorStateChange(editorState: any) {
    this.setState({
      editorState,
    });
    const text = draftToHtml(convertToRaw(editorState.getCurrentContent()));
    if (this.props.onChange) {
      this.props.onChange(text);
    }
  }

  uploadImageCallBack(file: any) {
    return new Promise((resolve, reject) => {
      let param = new FormData();
      param.append('ofile', file);
      param.append('ofile_class_code', 'richEditor');
      request
        .post('ofile/upload', param, {
          headers: { 'Content-Type': 'multipart/form-data' },
        })
        .then((result) => {
          resolve({
            data: {
              link: CONSTANT.SERVER_ADDR + result.data.url,
            },
          });
        })
        .catch((error) => {
          reject(error.data.data.message);
        });
    });
  }

  render() {
    return (
      <div>
        <Editor
          editorClassName={'richEditorContent'}
          localization={{ locale: 'zh' }}
          editorState={this.state.editorState}
          onEditorStateChange={this.onEditorStateChange}
          toolbar={{
            image: {
              uploadCallback: this.uploadImageCallBack,
              previewImage: true,
              urlEnabled: false,
            },
          }}
        />
      </div>
    );
  }
}
